package cn.yangliu.shiro;

import cn.yangliu.comm.CommConst;
import cn.yangliu.comm.entity.swagger.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class ShiroFormAuthenticationFilter extends FormAuthenticationFilter {

    @Override
    protected boolean onAccessDenied(ServletRequest request,
                                     ServletResponse response) throws Exception {

        if (isLoginRequest(request, response)) {
            if (isLoginSubmission(request, response)) {
                if (log.isTraceEnabled()) {
                    log.trace("Login submission detected.  Attempting to execute login.");
                }
                return executeLogin(request, response);
            } else {
                if (log.isTraceEnabled()) {
                    log.trace("Login page view.");
                }
                //allow them to see the login page ;)
                return true;
            }
        } else {
            if (log.isTraceEnabled()) {
                log.trace("Attempting to access a path which requires authentication.  Forwarding to the " +
                        "Authentication url [" + getLoginUrl() + "]");
            }
            if (ShiroWebUtils.checkJsonAjax((HttpServletRequest) request)) {
                JsonResult result = new JsonResult();
                result.setCode(CommConst.LOGIN_ERROR_CODE);
                result.setMsg("请先登录");
                ShiroWebUtils.printData(result, (HttpServletResponse) response);
            } else {
                saveRequestAndRedirectToLogin(request, response);
            }


            return false;
        }

    }

    @Override
    protected boolean onLoginSuccess(AuthenticationToken token,
                                     Subject subject, ServletRequest request, ServletResponse response)
            throws Exception {

        if (ShiroWebUtils.checkJsonAjax((HttpServletRequest) request)) {
            JsonResult result = new JsonResult();
            result.setMsg("登录成功");
            ShiroWebUtils.printData(result, (HttpServletResponse) response);
        } else {
            WebUtils.issueRedirect(request, response, getSuccessUrl());
        }
        return false;
    }


}
